<template>
  <div class="container">
    <div class="main">
      <div class="main_content">
        <div class="main_table">
          <!-- data-source 数据源,column 列名  row-selection列表项是否可选择	-->
          <!-- rowSelection 是计算属性进行加工处理 -->
          <a-table
            :scroll="{ y: 600 }"
            rowKey="id"
            :row-selection="{
              selectedRowKeys: selectedRowKeys,
              onChange: onSelectChange,
            }"
            :columns="columns"
            :data-source="data"
            :pagination="pagination"
            @change="handleTableChange"
          >
            <!-- 作用域插槽 text 本身是每一列的所有属性 但是 column的配置是 dataIndex 是avaurl 所以text 就变成了每一类的avarurl -->
            <span slot="choice" slot-scope="record">
              <ul>
                <li v-for="(val, keys, i) in record.options" :key="i">
                  {{ keys }} : {{ val }}
                </li>
              </ul>
            </span>

            <span slot="score" slot-scope="text, record">
              <a-input
                placeholder="请添加分数"
                :defaultValue="record.score"
                v-model="record.score"
                @change="changeScore"
                :disabled="!record.focus"
              />
            </span>
          </a-table>
          <div class="showScore">
            已选中 {{ totalItem }} 题,已选分值为 {{ totalScore }} 分
          </div>
        </div>
      </div>
    </div>

    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdate"
      @refreshDataList="getRoleMessage"
    ></add-or-update>
  </div>
</template>
<script>
import AddOrUpdate from "./questionsDetail-add-or-update.vue";
export default {
  props: ["records", "totalScore", "totalItem"],
  components: {
    AddOrUpdate,
  },
  data() {
    return {
      selectedRowKeys: [], // Check here to configure the default column
      //保存所有分页请求回来的数据;
      totalMessage: [],
      currentItemArr: [],
      totallyItemArr: [],
      isInit: true,
      userFocusItem: 0,
      userFocusScore: 0,
      // 专门用于接收所有的类型
      questionTypeItem: [],
      idList: [],
      Update_idList: [],
      // 搜索框内容
      searchDetail: "",
      // 静态模态的出现
      addOrUpdateVisible: false,
      // 列名
      columns: [
        // title:列名; dataIndex: 对应数据源中的键值(kay)
        {
          title: "题目类型",
          dataIndex: "type",
        },
        {
          title: "题目详情",
          dataIndex: "content",
          width: 150,
        },
        {
          title: "题目分类",
          dataIndex: "category",
          filters: [],
          onFilter: (value, record) => record.category.includes(value),
        },
        {
          title: "题目选项",
          key: "choice",
          scopedSlots: { customRender: "choice" },
          width: 200,
        },
        {
          title: "题目答案",
          dataIndex: "answers",
        },
        {
          title: "题目分数",
          key: "score",
          scopedSlots: { customRender: "score" },
        },
      ],
      // 数据源
      data: [
        //  键值key 对应列名, key为Vue 需要key 可以忽略
      ],
      pagination: {
        defaultPageSize: 5, // 默认当前页数
        defaultPageSize: 5, // 默认当前页显示数据的大小
        position: "bottom",
        pageSize: 20,
        pageSizeOptions: ["10", "15", "20", "25"],
        current: 1,
        total: 0,
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条";
        },
        showQuickJumper: true,
        showSizeChanger: true,
      },
      //   表头的配置条件
      sortedInfo: null,
    };
  },
  created() {
    this.searchRole();
    this.init();
  },
  mounted() {},
  methods: {
    // 设置 用户选中之后的回调
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed:123 ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
      let ids = [];
      selectedRowKeys.forEach((item) => {
        ids.push(item);
      });
      this.idList = ids;
      // 选中后 对应的分数框框 解封
      this.onFoucsAbleToModifyScore();
      this.$emit(
        "getFocusItemInTable",
        this.selectedRowKeys,
        this.totalMessage
      );
    },
    // 选中后 用户可以
    onFoucsAbleToModifyScore() {
      // 若改变的分数 也要传回去  而不是不修改
      this.data.forEach((item) => {
        item.focus = false;
      });
      this.selectedRowKeys.forEach((key) => {
        this.data.forEach((item) => {
          if (item.id == key) {
            item.focus = true;
          }
        });
      });
    },
    async init() {
      // 获取分类的id questionTypeItem
      const { data: res } = await this.$http.get("/question/category/all");
      this.questionTypeItem = res.data;
      this.columns[2].filters = this.filterType;

      this.data.forEach((item) => {
        item.focus = false;
      });
      this.idList.forEach((key) => {
        let flag = false;
        this.data.forEach((item) => {
          if (item.id == key) {
            flag = true;
            this.selectedRowKeys.push(key);
          }
        });
      });
      console.log("123213213213", this.idList);
    },
    changeScore() {
      this.$emit(
        "getFocusItemInTable",
        this.selectedRowKeys,
        this.totalMessage
      );
    },
    // 分页点击切换
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      let that = this;
      that.sortedInfo = sorter;
      // 通过点击 点击 改变current 中的属性 再影响pagination
      const pager = { ...that.pagination };
      pager.current = pagination.current;
      that.pagination = pager;
      this.currentItemArr.forEach((item) => {
        this.totallyItemArr.push(item);
      });

      this.searchRole();
    },
    // 分页查询
    async getRoleMessage(val) {
      this.searchRole();
    },
    // 分页查询显示
    async searchRole() {
      const { data: res } = await this.$http.get(
        `/admin/questions?page=${this.pagination.current}&size=${this.pagination.pageSize}`
      );

      this.pagination.total = Number(res.data.total);
      let tmpdata = res.data.records;
      tmpdata.forEach((item) => {
        if (item.type == 1) {
          item.type = "单选题";
        } else if (item.type == 2) {
          item.type = "多选题";
        } else {
          item.type = "判断题";
        }
      });
      tmpdata.forEach((item) => {
        item.score = 5;
        item.focus = false;
      });
      // 设置分数的默认值
      // 查看是否默认选中

      if (this.records) {
        //如果是修改操作
        for (let key in this.records.questions) {
          this.Update_idList.push(key);
          if (this.isInit == true) {
            this.selectedRowKeys.push(key);
          }
        }

        this.Update_idList = this.unique(this.Update_idList);

        // 默认配置 每个人都没有选中
        this.Update_idList.forEach((items) => {
          //items 为id
          tmpdata.forEach((item) => {
            // 每一项都设置成false
            if (item.id == items) {
              //遍历id 判断 用户是否选中这一行
              item.focus = true;
              item.score = this.records.questions[items];
            }
            // TODO: 将totalMessage 进行遍历 把所有重复项不添加进来
            this.totalMessage.push(item);
          });
        });
        // 修改操作为的是 即使不修改 也将值传出去4
        if (this.isInit == true) {
          this.isInit = false;
          this.$emit(
            "getFocusItemInTable",
            this.Update_idList,
            this.totalMessage
          );
        } else {
          this.$emit(
            "getFocusItemInTable",
            this.selectedRowKeys,
            this.totalMessage
          );
        }
      } else {
        // TODO:
        tmpdata.forEach((item) => {
          this.totalMessage.push(item);
        });
      }

      console.log("totalData", this.totalMessage);
      this.data = tmpdata;
    },

    unique(arr) {
      return Array.from(new Set(arr));
    },
  },
  computed: {
    filterType() {
      let list = [];
      this.questionTypeItem.forEach((item) => {
        let obj = {};
        obj.text = item.name;
        obj.value = item.name;
        list.push(obj);
      });
      return list;
    },

    //   表格选中的配置项
  },
};
</script>
<style  lang='less' scoped>
.container {
  box-sizing: border-box;
  display: flex;
  background-color: #fff !important ;
  padding: 0 0 !important;
  .main {
    width: 100%;
    overflow: hidden !important;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-items: center;
    // box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    .main_content {
      width: 100%;
      height: 100%;
      background-color: #fff;
      border-radius: 10px;
      .main_header {
        display: flex;
        margin-bottom: 25px;
        .main_table {
          margin-top: 50px;
        }
      }
    }
  }
}
/deep/ .ant-table-thead > tr > th,
.ant-table-tbody > tr > td {
  text-align: center;
}
/deep/ .ant-table-tbody > tr > td {
  text-align: center !important;
}
.disableColor {
  color: #eee;
}
li {
  list-style: none;
  margin-top: 10px;
}

/deep/ .ant-table-body {
  //样式穿透
  overflow-y: auto !important;
}
</style>